package com.bizdk.generator.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bizdk.generator.common.page.PageResult;
import com.bizdk.generator.common.query.Query;
import com.bizdk.generator.entity.gen.TypeMapping;
import com.bizdk.generator.mapper.TypeMappingMapper;
import com.bizdk.generator.service.TypeMappingService;
import lombok.AllArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 字段类型管理
 */
@AllArgsConstructor
@Service
public class TypeMappingServiceImpl extends ServiceImpl<TypeMappingMapper, TypeMapping>
        implements TypeMappingService {
    
    @Override
    public PageResult<TypeMapping> page(Query query) {
        IPage<TypeMapping> page = baseMapper.selectPage(new Page<>(query.getPageNum(), query.getPageSize()), query.getWrapper());
        return new PageResult<>(page.getRecords(), page.getTotal());
    }
    
    @Override
    public Map<String, TypeMapping> getMap() {
        List<TypeMapping> list = baseMapper.selectList(null);
        Map<String, TypeMapping> map = new LinkedHashMap<>(list.size());
        for (TypeMapping entity : list) {
            map.put(entity.getColumnType().toLowerCase(), entity);
        }
        return map;
    }
    
    @Override
    public Set<String> getPackageByTableId(Long tableId) {
        Set<String> importList = baseMapper.getPackageByTableId(tableId);
        
        return importList.stream().filter(StrUtil::isNotBlank).collect(Collectors.toSet());
    }
    
    @Override
    public Set<String> listAttrType() {
        return baseMapper.listAttrType();
    }
    
    @Override
    public boolean save(TypeMapping entity) {
        entity.setCreateTime(new Date());
        boolean saveFlag = false;
        try {
            saveFlag = super.save(entity);
        } catch (DuplicateKeyException dkex) {
            dkex.printStackTrace();
        }
        return saveFlag;
    }
}